package gui;

import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import javax.imageio.ImageIO;

import settings.Settings;
public class GameImagesStore {
	private static GameImagesStore single = new GameImagesStore();
	public static GameImagesStore get() {
		return single;
	}
	private HashMap sprites = new HashMap();
	public GameImage getSprite(String ref, int height, int width) {
		if (sprites.get(ref) != null) {
			return (GameImage) sprites.get(ref);
		}
		BufferedImage sourceImage = null;
		
		try {
			URL url = this.getClass().getClassLoader().getResource(ref);
			if (url == null) {
				fail("Can't find ref: "+ref);
			}
			sourceImage = ImageIO.read(url);
			sourceImage = this.resizeImage(sourceImage, height, width);
			
		} catch (IOException e) {
			fail("Failed to load: "+ref);
		}
		GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
		Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
		image.getGraphics().drawImage(sourceImage,0,0,null);
		GameImage img = new GameImage(image);
		sprites.put(ref,img);
		
		return img;
	}
	public static BufferedImage resizeImage(BufferedImage img, int newW, int newH) {  
	     int w = img.getWidth();  
	     int h = img.getHeight();  
	           
	     BufferedImage resizedImage = new BufferedImage(newW, newH, img.getType());  
	     Graphics2D g = resizedImage.createGraphics();  
	     g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
	             RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
	     g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);  
	     g.dispose();  
	           
	return resizedImage;  
} 
	private void fail(String message) {
		System.err.println(message);
		System.exit(0);
	}
}